package 原子类;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2022-08-29 11:07
 **/
public class AtomicIntegerFieldUpdaterDemo {

    public static void main(String[] args) {
        final BankAccount bankAccount = new BankAccount();

        final CountDownLatch countDownLatch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 1000; j++) {
                        bankAccount.add();
                    }
                } finally {
                    countDownLatch.countDown();
                }

            }, String.valueOf(i)).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(bankAccount.getMoney());
    }
}

class BankAccount{

    private String bankName = "CCB";

    public volatile int money = 0;

    private AtomicIntegerFieldUpdater<BankAccount> integerFieldUpdater = AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "money");

    public void add() {
        integerFieldUpdater.getAndIncrement(this);
    }

    public Integer getMoney() {
        return money;
    }

}
